<template>
  <div class="comments-list-container">
    <div class="page-header">
      <h2>评论管理</h2>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-filter">
      <el-input
        v-model="searchContent"
        placeholder="请输入评论内容"
        style="width: 300px; margin-right: 10px;"
        clearable
      />
      <el-select
        v-model="searchStatus"
        placeholder="请选择评论状态"
        style="width: 150px; margin-right: 10px;"
        clearable
      >
        <el-option label="正常" value="1" />
        <el-option label="隐藏" value="0" />
      </el-select>
      <el-select
        v-model="searchRating"
        placeholder="请选择评分"
        style="width: 150px; margin-right: 10px;"
        clearable
      >
        <el-option label="1星" value="1" />
        <el-option label="2星" value="2" />
        <el-option label="3星" value="3" />
        <el-option label="4星" value="4" />
        <el-option label="5星" value="5" />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 评论列表 -->
    <el-table :data="commentsList.records" style="width: 100%" v-loading="loading">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="评论ID" width="80" />
      <el-table-column prop="userId" label="用户ID" width="100" />
      <el-table-column prop="goodId" label="商品ID" width="100" />
      <el-table-column prop="content" label="评论内容" :show-overflow-tooltip="true">
        <template #default="scope">
          <div class="comment-content" :title="scope.row.content">
            {{ scope.row.content }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="rating" label="评分" width="100">
        <template #default="scope">
          <div class="rating-stars">
            <el-rate :value="scope.row.rating" disabled />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="images" label="评论图片" width="120">
        <template #default="scope">
          <el-image
            v-if="scope.row.images && scope.row.images.length > 0"
            :src="getFirstImage(scope.row.images)"
            :preview-src-list="getImageList(scope.row.images)"
            style="width: 40px; height: 40px;"
            fit="cover"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="danger" link @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="commentsList.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

// 表格数据
const commentsList = ref({ records: [], total: 0 });
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索
const searchContent = ref('');
const searchStatus = ref('');
const searchRating = ref('');

// 加载评论列表
const loadCommentsList = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      content: searchContent.value || undefined,
      status: searchStatus.value || undefined,
      rating: searchRating.value || undefined
    };
    const res = await axios.get('/api/comment', { params });
    if (res.data.code === 200 && res.data.data) {
      commentsList.value = res.data.data;
    }
  } catch (error) {
    ElMessage.error('加载评论列表失败');
    console.error('加载评论列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 获取评论的第一张图片
const getFirstImage = (images: string) => {
  try {
    const imageArray = JSON.parse(images);
    return imageArray && imageArray.length > 0 ? imageArray[0] : '';
  } catch {
    return '';
  }
};

// 获取评论的图片列表（用于预览）
const getImageList = (images: string) => {
  try {
    const imageArray = JSON.parse(images);
    return Array.isArray(imageArray) ? imageArray : [];
  } catch {
    return [];
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadCommentsList();
};

// 重置搜索
const resetSearch = () => {
  searchContent.value = '';
  searchStatus.value = '';
  searchRating.value = '';
  currentPage.value = 1;
  loadCommentsList();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  loadCommentsList();
};

// 当前页变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  loadCommentsList();
};

// 删除评论
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const res = await axios.delete(`/api/comment?idList=${id}`);
    if (res.data.code === 200) {
      ElMessage.success('删除成功');
      loadCommentsList();
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
      console.error('删除失败:', error);
    }
  }
};

// 状态改变
const handleStatusChange = async (row: any) => {
  try {
    await axios.put('/api/comment', {
      id: row.id,
      status: row.status
    });
    ElMessage.success('状态修改成功');
  } catch (error) {
    // 恢复原来的值
    row.status = row.status === 1 ? 0 : 1;
    ElMessage.error('状态修改失败');
    console.error('状态修改失败:', error);
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadCommentsList();
});
</script>

<style scoped>
.comments-list-container {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.search-filter {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.comment-content {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.rating-stars .el-rate {
  display: inline-flex;
}
</style>